<script setup lang="ts">
import { ref, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { UploadFilled, Picture, Delete, ArrowRight } from '@element-plus/icons-vue'
import { uploadAndPreprocessImage, getFullStaticUrl } from '@/api'
import { useImageStore } from '@/stores/image'
import { useRouter } from 'vue-router'

const router = useRouter()
const imageStore = useImageStore()

// 图片相关的响应式数据
const imageUrl = ref('')
const rawFile = ref<File | null>(null)
const loadingPreprocess = ref(false)
const fileInfo = ref({
  name: '',
  size: 0
})

// 计算属性
const canPreprocess = computed(() => {
  return !!imageUrl.value && !loadingPreprocess.value
})

// 方法
const handleBeforeUpload = (file: File) => {
  // 检查文件类型，支持常见图片格式
  const isImage = /\.(jpg|jpeg|png|bmp)$/i.test(file.name)
  if (!isImage) {
    ElMessage.error('只能上传 JPG、JPEG、PNG、BMP 格式的图片！')
    return false
  }
  
  // 检查文件大小，限制为10MB
  const isLt10M = file.size / 1024 / 1024 < 10
  if (!isLt10M) {
    ElMessage.error('图片大小不能超过 10MB!')
    return false
  }
  
  return true
}

const handleCustomUpload = async (options: any) => {
  const { file } = options
  handleSuccess(null, { raw: file })
}

const handleSuccess = (response: any, uploadFile: any) => {
  if (!uploadFile?.raw) return
  imageUrl.value = URL.createObjectURL(uploadFile.raw)
  rawFile.value = uploadFile.raw
  fileInfo.value = {
    name: uploadFile.raw.name,
    size: uploadFile.raw.size
  }
  imageStore.resetImages()
  ElMessage.success('图片上传成功')
}

const handleRemove = () => {
  imageUrl.value = ''
  rawFile.value = null
  fileInfo.value = { name: '', size: 0 }
  imageStore.resetImages()
}

const handlePreprocessImage = async () => {
  if (!rawFile.value) return
  loadingPreprocess.value = true
  try {
    console.log('开始预处理图片:', rawFile.value.name)
    const res = await uploadAndPreprocessImage(rawFile.value)
    console.log('预处理结果:', res)
    
    if (res && res.preprocessed_image_url) {
      imageStore.setPreprocessedImage(
        getFullStaticUrl(res.preprocessed_image_url), 
        res.preprocessed_image_path
      )
      ElMessage.success('图片预处理成功')
      router.push('/preprocess')
    } else {
      throw new Error('预处理响应格式不正确')
    }
  } catch (e: any) {
    console.error('预处理错误详情:', e)
    const errorMsg = e.response?.data?.error || e.message || '图片预处理失败'
    ElMessage.error(errorMsg)
  } finally {
    loadingPreprocess.value = false
  }
}
</script>

<template>
  <div class="upload-view">
    <div class="page-header">
      <h2>图片上传</h2>
      <p class="subtitle">上传包含车辆的图片进行检测识别</p>
    </div>
    
    <el-card class="section-card" shadow="hover">
      <template #header>
        <div class="card-header">
          <span>原始图片上传</span>
          <el-tag size="small" type="info">支持 JPG、JPEG、PNG、BMP 格式</el-tag>
        </div>
      </template>
      <el-upload
        class="upload-area"
        drag
        :auto-upload="true"
        :show-file-list="false"
        :before-upload="handleBeforeUpload"
        :http-request="handleCustomUpload"
        :on-remove="handleRemove"
      >
        <template #trigger>
          <div class="upload-trigger">
            <el-icon class="el-icon--upload"><upload-filled /></el-icon>
            <div class="el-upload__text">
              <span class="upload-highlight">拖拽图片</span>到此处上传
              <div class="upload-or">或</div>
              <el-button type="primary" plain>点击选择文件</el-button>
            </div>
          </div>
        </template>
      </el-upload>
      
      <div class="preview-section" v-if="imageUrl">
        <div class="preview-header">
          <h3>图片预览</h3>
          <el-button type="danger" link @click="handleRemove">
            <el-icon><Delete /></el-icon>
            删除图片
          </el-button>
        </div>
        <el-image :src="imageUrl" fit="contain" class="preview-img">
          <template #error>
            <div class="image-slot">
              <el-icon><Picture /></el-icon>
              <span>图片加载失败</span>
            </div>
          </template>
        </el-image>
        <div class="image-info">
          <el-descriptions :column="2" border size="small">
            <el-descriptions-item label="文件名">
              {{ fileInfo.name }}
            </el-descriptions-item>
            <el-descriptions-item label="文件大小">
              {{ ((fileInfo.size || 0) / 1024).toFixed(1) }}KB
            </el-descriptions-item>
          </el-descriptions>
        </div>
      </div>
      <el-empty
        v-else
        class="image-empty"
        description="等待上传图片"
      >
        <template #image>
          <el-icon :size="48" color="#909399"><Picture /></el-icon>
        </template>
      </el-empty>
      
      <div class="action-section" v-if="imageUrl">
        <el-button
          type="primary"
          class="action-btn"
          :loading="loadingPreprocess"
          :disabled="!canPreprocess"
          @click="handlePreprocessImage"
        >
          <el-icon><ArrowRight /></el-icon>
          开始预处理
        </el-button>
        <p class="help-text" v-if="!loadingPreprocess">
          点击"开始预处理"进入下一步
        </p>
      </div>
    </el-card>
  </div>
</template>

<style scoped>
.upload-view {
  padding: 24px;
  height: 100%;
  display: flex;
  flex-direction: column;
  gap: 24px;
}

.page-header {
  margin-bottom: 8px;
}

.page-header h2 {
  font-size: 1.8rem;
  font-weight: 600;
  color: var(--text-color);
  margin-bottom: 8px;
}

.subtitle {
  color: #606266;
  font-size: 1rem;
}

.section-card {
  flex: 1;
  background: #fff;
  border-radius: var(--border-radius);
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
  transition: all var(--transition-speed);
}

.section-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.1);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 4px;
}

.card-header span {
  font-size: 1.1rem;
  font-weight: 500;
  color: var(--text-color);
}

.upload-area {
  width: 100%;
  margin-bottom: 24px;
}

.upload-trigger {
  padding: 32px 0;
}

:deep(.el-upload) {
  width: 100%;
  display: block;
}

:deep(.el-upload-dragger) {
  width: 100%;
  padding: 0;
  border: 2px dashed #dcdfe6;
  background: #f8fafc;
  transition: all var(--transition-speed);
}

:deep(.el-upload-dragger:hover) {
  border-color: var(--primary-color);
  background: var(--primary-light);
}

.el-icon--upload {
  font-size: 48px;
  color: var(--primary-color);
  margin-bottom: 16px;
}

.el-upload__text {
  color: #606266;
  font-size: 1rem;
  text-align: center;
}

.upload-highlight {
  color: var(--primary-color);
  font-weight: 600;
}

.upload-or {
  margin: 12px 0;
  color: #909399;
  font-size: 0.9rem;
}

:deep(.el-button) {
  --el-button-bg-color: transparent;
  --el-button-border-color: var(--primary-color);
  --el-button-text-color: var(--primary-color);
  --el-button-hover-text-color: var(--primary-color);
  --el-button-hover-bg-color: var(--primary-light);
  --el-button-hover-border-color: var(--primary-color);
  font-size: 1rem;
  height: 40px;
  padding: 0 24px;
}

:deep(.el-button:hover) {
  color: var(--primary-color);
}

.preview-section {
  margin-top: 24px;
  padding-top: 24px;
  border-top: 1px dashed #dcdfe6;
}

.preview-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.preview-header h3 {
  font-size: 1rem;
  font-weight: 500;
  color: var(--text-color);
  margin: 0;
}

.preview-img {
  width: 100%;
  height: 300px;
  object-fit: contain;
  background: #f8fafc;
  border-radius: var(--border-radius);
  margin-bottom: 16px;
  border: 1px solid #ebeef5;
}

.image-slot {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
  color: #909399;
  gap: 8px;
}

.image-info {
  margin: 16px 0;
}

.image-empty {
  height: 240px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  background: #f8fafc;
  border-radius: var(--border-radius);
  margin: 24px 0;
  border: 1px solid #ebeef5;
}

.action-section {
  text-align: center;
  margin-top: 24px;
}

.action-btn {
  min-width: 180px;
  height: 44px;
  font-size: 1rem;
}

.help-text {
  margin-top: 12px;
  color: #909399;
  font-size: 0.9rem;
}

:deep(.el-descriptions) {
  padding: 16px;
  background: #f8fafc;
  border-radius: var(--border-radius);
}

@media (max-width: 768px) {
  .upload-view {
    padding: 16px;
    gap: 16px;
  }

  .page-header h2 {
    font-size: 1.5rem;
  }

  .preview-img {
    height: 240px;
  }

  .action-btn {
    width: 100%;
  }
}
</style> 